package com.system.analysis;

import java.util.ArrayList;
import java.util.List;

import com.system.analysis.excel.ExcelAnalysisResult;
import com.system.analysis.excel.ExcelAnalysisTitle;
import com.system.comm.utils.FrameJsonUtil;
import com.system.comm.utils.FrameStringUtil;

/**
 * 分析Excel的文本
 * @author yuejing
 * @date   2021年5月22日
 */
public class ExcelAnalysisUtil {

	/**
	 * 分析
	 */
	public static ExcelAnalysisResult analysis(String title, String analysisText) {
		ExcelAnalysisResult result = new ExcelAnalysisResult();
		List<ExcelAnalysisTitle> titleList = analysisTitle(title);
		result.setTitleList(titleList);
		List<List<String>> dataList = analysisData(titleList, analysisText);
		result.setDataList(dataList);
		return result;
	}
	
	private static List<List<String>> analysisData(List<ExcelAnalysisTitle> titleList, String analysisText) {
		List<List<String>> excelDataList = new ArrayList<List<String>>();
		List<String> dataList = FrameStringUtil.toArray(analysisText, "\n");
		for (String string : dataList) {
			if (FrameStringUtil.isEmpty(string)) {
				continue;
			}
			List<String> values = new ArrayList<>();
			String[] itemArr = string.trim().split("\t");
			for (String string1 : itemArr) {
				if (FrameStringUtil.isEmpty(string1)) {
					// 没有数据的情况，添加空字符串
					values.add("");
					continue;
				}
				List<String> cld1List = FrameStringUtil.toArray(string1, " ");
				for (String string2 : cld1List) {
					values.add(string2.trim());
				}
			}
			excelDataList.add(values);
		}
		return excelDataList;
	}

	private static List<ExcelAnalysisTitle> analysisTitle(String title) {
		List<ExcelAnalysisTitle> excelTitleList = new ArrayList<ExcelAnalysisTitle>();
		List<String> titleList = FrameStringUtil.toArray(title, "\t");
		int index = 0;
		for (String string : titleList) {
			if (FrameStringUtil.isEmpty(string)) {
				continue;
			}
			List<String> cld1List = FrameStringUtil.toArray(string, " ");
			for (String string1 : cld1List) {
				if (FrameStringUtil.isEmpty(string1)) {
					continue;
				}
				excelTitleList.add(new ExcelAnalysisTitle(index, string1.trim()));
				index ++;
			}
		}
		return excelTitleList;
	}

	public static void main(String[] args) {
		String title = "外网接口	映射目的IP	源端口  目标端口	转换目标端口为	映射所有	发布服务器";
		String analysisText = "210.21.201.139_理财外包服务sftp服务器_2002	WAN1	10.191.0.126	0	2003	2002	否\r\n" + 
				"						\r\n" + 
				"210.21.201.139讯投porxy_56000		10.191.0.93	0	56000	56000	否\r\n" + 
				"						\r\n" + 
				"210.21.201.139xtporxy_59000	WAN1	10.191.0.93	0	59000	59000	否\r\n" + 
				"						\r\n" + 
				"210.21.201.139_投资宝典H5	WAN1	10.191.0.47	0	8222	8222	否\r\n";
		ExcelAnalysisResult result = ExcelAnalysisUtil.analysis(title, analysisText);
		System.out.println(FrameJsonUtil.toString(result));
	}
}